package com.maylann.ratiocheater.controller;

import com.maylann.ratiocheater.encoder.TorrentDecoder;
import com.maylann.ratiocheater.encoder.TorrentDictionary;
import com.maylann.ratiocheater.model.Task;
import com.maylann.ratiocheater.model.Torrent;
import com.maylann.ratiocheater.transform.TorrentMapper;
import com.maylann.ratiocheater.transform.TransformationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * by Maylann
 */
@Controller
public class FileController {

    private TorrentMapper torrentMapper;
    private TorrentDecoder torrentDecoder;

    @Autowired
    public FileController(TorrentMapper torrentMapper, TorrentDecoder torrentDecoder) {
        this.torrentMapper = torrentMapper;
        this.torrentDecoder = torrentDecoder;
    }

    /**
     * Open a .torrent file
     *
     * @param torrentFilename The path + name to the torrentFile
     * @return The information of the torrent file mapped into a Torrent object
     */
    public Torrent openTorrentFile(String torrentFilename) throws IOException, TransformationException {
        TorrentDictionary<String,Object> torrentDictionary = torrentDecoder.decode(torrentFilename);
        TorrentDictionary<String, Object> infoDictionary =
                (TorrentDictionary<String, Object>) torrentDictionary.get(TorrentDictionary.INFO);
        String infoHash = torrentDecoder.getInfoHashUrlEncoded(infoDictionary);
        return torrentMapper.map(torrentDictionary, infoHash);
    }


    /**
     * Save the progress of a cheat task to a .properties file
     *
     */
    public boolean saveProgress(Task task) {
        return true;
    }


    /**
     * Read the progress of the torrent files in the .properties file to resume cheat tasks.
     *
     * @return List of saved progress
     */
    public List<Task> loadProgressFile() {
        return new ArrayList<Task>();
    }
}
